import cv2
import numpy as np
import pytesseract
from pytesseract import Output

image = cv2.imread('/Users/zyy/Downloads/8888.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# edges = cv2.Canny(gray, 50, 150)
# cv2.imshow('image', edges)
# cv2.waitKey(0)

# lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, minLineLength=100, maxLineGap=10)

# angle_list = []
# for line in lines:
#     x1, y1, x2, y2 = line[0]
#     angle = np.arctan2(y2 - y1, x2 - x1) * 180 / np.pi
#     angle_list.append(angle)
#     cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)

# cv2.imshow('image', image)
# cv2.waitKey(0)
# # print(angle_list)
# threshold = 5
# mean_angle = np.mean(angle_list)
# print(mean_angle)
# if abs(mean_angle) < threshold:
#     print("The word is horizontal")
# else:
#     print("The word is vertical")


results = pytesseract.image_to_osd(image, output_type=Output.DICT)
print(results)
print(results['orientation'])
rotate_matrix = cv2.getRotationMatrix2D((image.shape[1] / 2, image.shape[0] / 2), results['orientation'], 1)
rotate_image = cv2.warpAffine(image, rotate_matrix, (image.shape[1], image.shape[0]))
cv2.imshow('image', rotate_image)
cv2.waitKey(0)